package org.jeecg.modules.iot.aliyun;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import org.jeecg.modules.iot.common.AppConfig;
import org.jeecg.modules.iot.tools.JsonUtils;

public class MnsThread extends Thread {

    private AppConfig appConfig;

    private MnsUtils mnsUtils;

    public MnsThread(AppConfig appConfig, MnsUtils mnsUtils) {
        this.appConfig = appConfig;
        this.mnsUtils = mnsUtils;
    }

    @Override
    public void run() {
        super.run();
        String endPoint = "http://" + appConfig.getMnsEndpoint();

        CloudAccount account = new CloudAccount(appConfig.getAccessKeyId(), appConfig.getAccessKeySecret(), endPoint);
        MNSClient client = account.getMNSClient();
        CloudQueue queue = client.getQueueRef("aliyun-iot-" + appConfig.getProductKey()); //参数请输入IoT自动创建的队列名称
        Message popMsg = null;
        while (!Thread.interrupted()) {
            try {
                // 获取消息
                popMsg = queue.popMessage(10); //长轮询等待时间为10秒
                if (popMsg != null) {
                    MessageBody messageBody = JsonUtils.toObject(popMsg.getMessageBody(), MessageBody.class);
                    mnsUtils.handlerMessage(messageBody);
                }

            }
            catch (Exception e) {
                e.printStackTrace();
                mnsUtils.setException(e);

                if(e.getCause() instanceof InterruptedException){
                    break;
                }
            } finally {
                if (queue != null && popMsg != null) {
                    try {
                        //从队列中删除消息
                        queue.deleteMessage(popMsg.getReceiptHandle());
                    } catch (Exception e) {
                        e.printStackTrace();
                        mnsUtils.setException(e);
                    } finally {
                        popMsg = null;
                    }
                }
            }
        }
    }
}
